package com.platform.common.utils.wx;

import org.springframework.boot.configurationprocessor.json.JSONException;
import org.springframework.boot.configurationprocessor.json.JSONObject;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

/**
 * 微信小程序获取accessToken
 */
public class GetAccessTokenUtil {
    // 网页授权接口
    public static String getAccessToken(String appid, String appsecret) {
        RestTemplate restTemplate = new RestTemplate();
        Map<String, String> params = new HashMap<>();
        params.put("APPID", appid);
        params.put("APPSECRET", appsecret);
        ResponseEntity<String> reponseEntity = restTemplate.getForEntity("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={APPID}&secret={APPSECRET}", String.class, params);
        String access_tokenStr = reponseEntity.getBody();
        try {
            JSONObject jsonObject = new JSONObject(access_tokenStr);
            String accessToken = String.valueOf(jsonObject.get("access_token"));
            return accessToken;
        }catch (JSONException e) {}
        return "";
    }
}
